package vip.zhenzicheng.concurrent_program.jmm;

/**
 * 可见性demo
 * -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly -Xcomp
 *
 * @author zhenzicheng
 * @date 2022-06-29 10:32
 */
public class VisibilityTest {

  private volatile boolean flag = true;

  public static void main(String[] args) throws InterruptedException {
    VisibilityTest test = new VisibilityTest();

    // 线程threadA模拟数据加载场景
    Thread threadA = new Thread(() -> test.load(), "threadA");
    threadA.start();

    // 让threadA执行一会儿
    Thread.sleep(1000);
    // 线程threadB通过flag控制threadA的执行时间
    Thread threadB = new Thread(() -> test.refresh(), "threadB");
    threadB.start();

  }

  public static void shortWait(long interval) {
    long start = System.nanoTime();
    long end;
    do {
      end = System.nanoTime();
    } while (start + interval >= end);

  }

  public void refresh() {
    flag = false;
    System.out.println(Thread.currentThread().getName() + "修改flag");
  }

  public void load() {
    System.out.println(Thread.currentThread().getName() + "开始执行.....");
    int i = 0;
    while (flag) {
      i++;
      //TODO  业务逻辑

    }
    System.out.println(Thread.currentThread().getName() + "跳出循环: i=" + i);
  }
}
